import bus from '@/utils/bus'

export default function(options = {}) {
  const get = options.get || function () {}
  const add = options.add || function () {}
  const edit = options.edit || function () {}

  return {
    data() {
      return {
        loading: true,
        saving: false
      }
    },
    computed: {
      isDisableForm() {
        return this.loading || this.saving
      }
    },
    async created() {
      if (this.$route.query.mode == 'edit') {
        await this.load()
      } else {
        this.loading = false
      }
    },
    // 监听路由变化
    watch: {
      $route(to, from) {
        if (to.query.mode == 'edit') {
          this.load()
        }else{
          this.resetForm()
        }
      }
    },
    methods: {
      async load() {
        this.loading = true
        this.form = (await this.getDetail()).data
        console.log('查询form',this.form)
        this.loading = false
      },
      getDetail() {
        return get({id: this.$route.query.id, ids: this.$route.query.ids})
      },
      async save(options) {
        try {
          await this.validateForm()
          await this.$confirm('确定保存吗？','保存')
          this.saving = true
          const {invoiceFee=0,kickbackFee=0} = this.form
          if (this.$route.query.mode == 'edit') {
            await edit({data: { ...this.form,invoiceFee,kickbackFee}})
          } else {
            await add({data: { ...this.form,invoiceFee,kickbackFee}})
          }
          this.resetForm()
          this.$multiTab.open(options.redirect)
          // bus.$emit('open', {path: options.redirect})
        } catch (e) {
          console.log(e)
        }finally {
          setTimeout(() => {
            this.saving = false
          }, 500)
        }
      },
      validateForm() {
        return new Promise((resolve, reject) => {
          this.$refs.form.validate(valid => {
            if (valid && this.beforeSave()) {
              resolve()
            } else {
              reject()
            }
          })
        })
      }
    }
  }
}